package com.fucking.great.socket;

import cn.hutool.core.convert.ConverterRegistry;
import cn.hutool.core.io.BufferUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.socket.nio.NioServer;
import com.fucking.great.context.GreatMain;
import com.fucking.great.context.TxnContext;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.Locale;

public class SocketNIOServer {
    public static final Log log = LogFactory.get();

    public SocketNIOServer( ){
        this(8080,1024);
    }

    public SocketNIOServer(int port ){
        this(port,1024);
    }
    final NioServer server;
    public SocketNIOServer(int port ,final int capacity){
        server = new NioServer(port);
        server.setChannelHandler((sc)->{
            ByteBuffer readBuffer = ByteBuffer.allocate(capacity);
            try{
                //从channel读数据到缓冲区
                int readBytes = sc.read(readBuffer);
                SocketAddress remoteAddress = sc.getRemoteAddress();
                if (readBytes > 0) {
                    //Flips this buffer.  The limit is set to the current position and then
                    // the position is set to zero，就是表示要从起始位置开始读取数据
                    readBuffer.flip();
                    //eturns the number of elements between the current position and the  limit.
                    // 要读取的字节长度
                    byte[] bytes = new byte[readBuffer.remaining()];
                    //将缓冲区的数据读到bytes数组
                    readBuffer.get(bytes);
                    String body = StrUtil.utf8Str(bytes);

//                    Console.log("LocalAddress=【{}】，[{}]: {}",sc.getLocalAddress(), remoteAddress, body);
                    Object ret = doWrite(String.valueOf(remoteAddress),body);
                    sc.write(BufferUtil.createUtf8(String.valueOf(ret)));
                } else if (readBytes < 0) {
                    IoUtil.close(sc);
                }
            } catch (IOException e){
                throw new IORuntimeException(e);
            }
        });


    }

    public void listen(){
        server.listen();
    }

    public Object doWrite( String address, String request) throws IOException {
//        response = "收到消息：" + response;

        TxnContext context = TxnContext.getContext();
        Object invoke =  null;
        try {
            // 放入初始参数.
            JSONObject jsonRequest = JSONUtil.parseObj(request);
            context.putAll(jsonRequest);
            // 组装必要内容。
            context.setClientIp(address);
            //
            String path = context.getStr("path");
            // 地区属性.
            Locale locale ;
            String localeStr = context.getStr("locale");
            if(StrUtil.isBlank(localeStr)){
                locale = Locale.getDefault();
            }else {
                locale = ConverterRegistry.getInstance().convert(Locale.class, localeStr);
            }
            context.setLocale(locale);
            //
            context.setUrl(address+"/"+path);
            context.setType("tcp");
            //
            invoke =   GreatMain.doService(context);

        } catch (Throwable e) {
            log.trace(e);
        }
        return  invoke;
    }

    public static void main(String[] args) {
        ConverterRegistry converterRegistry = ConverterRegistry.getInstance();
        Locale zh_cn = converterRegistry.convert(Locale.class, "zh_CN");
        System.out.println(zh_cn.getCountry()+zh_cn);

        new SocketNIOServer().listen();

    }
}
